import QtQuick
import QtQuick.Layouts
import QtQuick.Dialogs
import QtQuick.Controls

import Fk
import Fk.Components.Common
import Fk.Widgets as W
import Fk.Pages.LunarLTK

// TODO 现在还用不了这个
// import Fk.Components.Chess.NChess
import "../../Components/Chess/NChess"

W.PageBase {
  id: roomScene

  property bool inMyTurn: false
  property var selectedPiece: null
  property var pieces: ({})
  property int roundCount: 0
  property bool proposedDraw: false

  property alias popupBox: popupBox

  // 将x和y对应到坐标
  // 若为黑方则翻转180度
  function convertPos(bX, bY) {
    let x = 62 * bX;
    let y = 62 * bY;

    if (Lua.evaluate("Self.role") === "black") {
      x = 434 - x;
      y = 434 - y;
    }

    return [x, y];
  }

  function moveTo(piece, bX, bY) {
    const [x, y] = convertPos(bX, bY);
    piece.x = x;
    piece.y = y;
    piece.boardX = bX;
    piece.boardY = bY;
  }

  states: [
    State { name: "notactive" },
    State { name: "active" }
  ]

  state: "notactive"
  transitions: [
    Transition {
      from: "*"; to: "notactive"
      ScriptAction {
        script: {
          roomScene.deActivate();
        }
      }
    }
  ]

  // Rectangle {
  //   id: shadowMask
  //   anchors.fill: parent
  //   color: '#2b2b2b'
  //   opacity: 0.75
  // }

  Rectangle {
    id: board
    color: "transparent"
    width: 496
    height: 496
    anchors.centerIn: parent

    // 定义棋盘上的90个交叉点
    Repeater {
      id: gridPoints
      model: 64
      Rectangle {
        color: "transparent"
        width: 62; height: 62;
        x: (index % 8) * 62
        y: Math.floor(index / 8) * 62
        z: 5
        property int xPos: index % 8
        property int yPos: Math.floor(index / 8)
        property bool enabled: false
        property bool beCircle: false

        Rectangle {
          width: 20
          height: 20
          radius: 10
          color: "black"
          opacity: 0.3
          anchors.centerIn: parent
          visible: parent.enabled & (!parent.beCircle)
        }

        Image {
          id: ellipseImg
          source: `${Cpp.path}/packages/chess-games/image/nchess/ellipse.png`
          anchors.fill: parent
          opacity: 0.3
          visible: parent.enabled & parent.beCircle
        }


        W.TapHandler {
          enabled: parent.enabled
          onTapped: {
            let luaPosId = (yPos + 1) * 10 + (xPos + 1)
            if (Lua.evaluate("Self.role") === "black") {
              luaPosId = (8 - yPos) * 10 + (8 - xPos)
            }
            Lua.call("UpdateRequestUI", "NChess.PointItem", luaPosId, "click", {
              selected: true,
            } );
          }
        }
      }
    }
    
    //棋盘 轨迹 指向框 -（白|黑）
    property var colorStyles: [
      [ '#ebecd0', '#739552', '#f5f682', '#b9ca43', '#b2c25b', '#fcfcd3' ], 
      [ '#ffffff', '#000000', '#636363', '#a7a7a7', '#777777', '#585858' ],
      [ '#ebecd0', '#b68860', '#ca993e', '#df8f45', '#918261', '#92785a' ],
      [ '#ebc7d2', '#b96c91', '#d47ae6', '#da558c', '#9c6393', '#cc91ae' ],
    ]
    property var colorStyle: colorStyles[0]

    //棋盘标记
    Repeater {
      id: boardGridRepeater
      model: 64
      Rectangle {
        id: broadGridStyle
        property int xPos: index % 8
        property int yPos: Math.floor(index / 8)
        property bool lastMove: false
        property bool justShow: false
        property bool hover: false
        property string gridColor: ((xPos + yPos) % 2 === 0) ? "white" : "black"

        property alias leftText: leftText
        property alias bottomText: bottomText

        color: "transparent"
        width: 62; height: 62;
        x: (index % 8) * 62
        y: Math.floor(index / 8) * 62

        Rectangle {
          id: boardGrid
          width: 62; height: 62;
          color: `${gridColor == "white" ? board.colorStyle[0] : board.colorStyle[1]}`
          anchors.fill: parent
        }

        Rectangle {
          id: boardPath
          color: `${gridColor == "white" ? board.colorStyle[2] : board.colorStyle[3]}`
          opacity: 1
          anchors.fill: parent
          visible: parent.lastMove || parent.justShow
        }

        Rectangle {
          color: "transparent"
          border.width: 3
          border.color: `${gridColor == "white" ? board.colorStyle[4] : board.colorStyle[5]}`
          visible: parent.hover
          anchors.fill: parent
        }

        Text {
          id: leftText
          text: "0"
          font.pixelSize: 10
          font.bold: true
          x: 3
          y: 1
          color: (parent.lastMove || parent.justShow)
            ? ((broadGridStyle.gridColor == "white") ? board.colorStyle[3] : board.colorStyle[2])
            : ((broadGridStyle.gridColor == "white") ? board.colorStyle[1] : board.colorStyle[0])
          visible: (index % 8) === 0
        }

        Text {
          id: bottomText
          text: "0"
          font.pixelSize: 12
          font.bold: true
          x: parent.width - 11
          y: parent.height - 18
          color: (parent.lastMove || parent.justShow)
            ? ((broadGridStyle.gridColor == "white") ? board.colorStyle[3] : board.colorStyle[2])
            : ((broadGridStyle.gridColor == "white") ? board.colorStyle[1] : board.colorStyle[0])
          visible: index > 55
        }
      }
    }
  }

  Photo {
    id: myPhoto
    anchors.left: board.right
    anchors.bottom: board.bottom
    anchors.leftMargin: 12

    onThinkingChanged: {
      if (!thinking) roomScene.deActivate();
    }
  }

  Photo {
    id: opponentPhoto
    anchors.right: board.left
    anchors.top: board.top
    anchors.rightMargin: 12
  }

  Rectangle {
    id: buttonArea
    width: 40
    height: 132
    color: "transparent"
    anchors.bottom: board.bottom
    anchors.right: board.left
    anchors.rightMargin: 12

    property alias penButton: penButton

    Rectangle {
      id: surrenderButton
      width: 40
      height: 40
      radius: 4
      color: '#ebeef0'
      anchors.top: parent.top   

      Image {
        source: `${Cpp.path}/packages/chess-games/image/nchess/surrender.png`
        sourceSize: Qt.size(40, 40)
        anchors.fill: parent
      }  

      MouseArea {
        anchors.fill: parent
        onPressed: {
          const surrenderCheck = Lua.call('CheckSurrenderAvailable')
          surrenderDialog.informativeText = surrenderCheck
          .map(str => `${str.text}（${str.passed ? '✓' : '✗'}）`)
          .join('<br>');
          surrenderDialog.open();
        }
      } 

      MessageDialog {
        id: surrenderDialog
        title: Lua.tr("Surrender")
        informativeText: ''
        buttons: MessageDialog.Ok | MessageDialog.Cancel
        onButtonClicked: function (button, role) {
          switch (button) {
            case MessageDialog.Ok: {
              const surrenderCheck =
              Lua.call('CheckSurrenderAvailable');
              if (surrenderCheck.length &&
              !surrenderCheck.find(check => !check.passed)) {
                roomScene.deActivate()
                Cpp.notifyServer("PushRequest", [
                  "surrender", true
                ].join(","));
              }
              surrenderDialog.close();
              break;
            }
            case MessageDialog.Cancel: {
              surrenderDialog.close();
            }
          }
        }
      }
    }

    Rectangle {
      id: armisticeButton
      width: 40
      height: 40
      radius: 4
      color: '#ebeef0'
      anchors.top: surrenderButton.bottom
      anchors.topMargin: 6   

      Image {
        source: `${Cpp.path}/packages/chess-games/image/nchess/armistice.png`
        sourceSize: Qt.size(40, 40)
        anchors.fill: parent
      }  

      MouseArea {
        anchors.fill: parent
        onPressed: {
          armisticeDialog.informativeText = `当前正在执棋： ${myPhoto.thinking === true ? "√" : "×"}<br>对局回合数大于20： ${roomScene.roundCount > 20 ? "√" : "×"}`
          armisticeDialog.open();
        }
      }

      MessageDialog {
        id: armisticeDialog
        title: Lua.tr("armistice")
        informativeText: '提和'
        buttons: MessageDialog.Ok | MessageDialog.Cancel
        onButtonClicked: function (button, role) {
          switch (button) {
            case MessageDialog.Ok: {
              if (myPhoto.thinking === true && roomScene.roundCount > 20) {
                if (!roomScene.proposedDraw) {
                  Cpp.notifyServer("PushRequest", [
                    "armistice", Lua.evaluate(`Self.role`)
                  ].join(","));
                  App.showToast(Lua.tr("Have proposed a draw"))
                } else {
                  App.showToast(Lua.tr("You can't proposed a seceond draw"))
                }
              }
              roomScene.proposedDraw = true
              surrenderDialog.close();
              break;
            }
            case MessageDialog.Cancel: {
              surrenderDialog.close();
            }
          }
        }
      }
    }

    Rectangle {
      id: penButton
      width: 40
      height: 40
      radius: 4
      color: '#ebeef0'
      anchors.top: armisticeButton.bottom
      anchors.topMargin: 6
      property string penCode: ""

      Image {
        source: `${Cpp.path}/packages/chess-games/image/nchess/share.png`
        sourceSize: Qt.size(40, 40)
        anchors.fill: parent
      }

      MouseArea {
        anchors.fill: parent
        onPressed: {
          Backend.copyToClipboard(parent.penCode);
          App.showToast(Lua.tr("Have copied PEN code"))
        }
      }
    }
  }

  GlowText {
    visible: Config.observing && !Config.replaying
    anchors.right: board.left
    anchors.bottom: board.bottom
    anchors.rightMargin: 12
    text: Lua.tr("Observing ...")
    color: "#4B83CD"
    font.family: Config.li2Name
    font.pixelSize: 48
  }

  Rectangle {
    id: gameOverRect
    width: 200
    height: 200
    radius: 8
    color: "#AAFFFFFF"
    visible: false

    anchors.left: board.right
    anchors.top: board.top
    anchors.leftMargin: 12

    ColumnLayout {
      anchors.centerIn: parent
      width: parent.width
      spacing: 15

      Text {
        id: winnerText
        font.pixelSize: 24
        font.bold: true
        Layout.alignment: Qt.AlignHCenter
      }

      W.ButtonContent {
        Layout.alignment: Qt.AlignHCenter
        text: Lua.tr("Back To Room")
        visible: !Config.observing

        onClicked: {
          Mediator.notify(this, Command.ResetRoomPage);
        }
      }

      W.ButtonContent {
        text: Lua.tr("Back To Lobby")
        Layout.alignment: Qt.AlignHCenter

        onClicked: {
          Mediator.notify(this, Command.IWantToQuitRoom);
        }
      }

      W.ButtonContent {
        id: repBtn
        Layout.alignment: Qt.AlignHCenter
        text: Lua.tr("Save Replay")
        visible: Config.observing && !Config.replaying // 旁观

        onClicked: {
          repBtn.visible = false;
          Mediator.notify(this, Command.IWantToSaveRecord);
        }
      }

      W.ButtonContent {
        id: bkmBtn
        Layout.alignment: Qt.AlignHCenter
        text: Lua.tr("Bookmark Replay")
        visible: !Config.observing && !Config.replaying // 玩家

        onClicked: {
          bkmBtn.visible = false;
          Mediator.notify(this, Command.IWantToBookmarkRecord);
        }
      }
    }
  }

  Loader {
    id: popupBox
    z: 999
    onSourceChanged: {
      if (item === null)
        return;
      item.finished.connect(() => {
        sourceComponent = undefined;
      });
      item.widthChanged.connect(() => {
        popupBox.moveToCenter();
      });
      item.heightChanged.connect(() => {
        popupBox.moveToCenter();
      });
      moveToCenter();
    }
    onSourceComponentChanged: sourceChanged();

    function moveToCenter() {
      item.x = Math.round((roomScene.width - item.width) / 2);
      item.y = Math.round(roomScene.height * 0.2 - item.height / 2);
    }
  }

  function addToChat(pid, raw, msg) {
    const photo = getPhoto(pid);
    chat.append(msg, raw);
    photo.chat(raw.msg);
  }

  function getPhoto(id) {
    if (id == Self.id) return myPhoto;
    if (id == opponentPhoto.playerid) return opponentPhoto;
  }

  function selectPiece(piece) {
    Lua.call("UpdateRequestUI", "NChess.PieceItem", piece.pieceId, "click", {
      selected: piece.selected,
    } );
  }

  // 根据玩家座位转换棋盘坐标
  function convertOrientation(position) {
    if (Self.seatNumber === 2) return position;
    return [8 - position[0], 8 - position[1]];
  }

  function applyChange(sender, uiUpdate) {
    uiUpdate["NChess.PieceItem"]?.forEach(pdata => {
      const piece = pieces[pdata.id];
      piece.selectable = pdata.enabled;
      piece.selected = pdata.selected;
    });

    uiUpdate["_delete"]?.forEach(dat => {
      if (dat.type == "NChess.PointItem") {
        const id = dat.id
        const x = id % 10
        const y = Math.floor(id / 10)
        let gridIdx = (y - 1) * 8 + (x - 1)
        if (Lua.evaluate("Self.role") === "black") {
          gridIdx = (8 - y) * 8 + (8 - x)
        }
        const item = gridPoints.itemAt(gridIdx);
        item.enabled = false;
        item.beCircle = false;
      }
    });
    uiUpdate["_new"]?.forEach(dat => {
      if (dat.type === "NChess.PointItem") {
        const id = dat.data.id
        const x = id % 10
        const y = Math.floor(id / 10)
        let xPos = x - 1 
        let yPos = y - 1
        let gridIdx = (y - 1) * 8 + (x - 1)
        if (Lua.evaluate("Self.role") === "black") {
          gridIdx = (8 - y) * 8 + (8 - x)
        }
        const item = gridPoints.itemAt(gridIdx);
        item.enabled = true;
        for (const id in pieces) {
          if (id === 0) continue 
          let p = pieces[id]         
          if (p.xPos === xPos && p.yPos === yPos && p.x > 0) {
            item.beCircle = true;
          }
        }
      }
    });
  }

  function initialPiece(id, _x, _y) {
    const component = Qt.createComponent("../../Components/Chess/NChess/Piece.qml")
    const [xAxis, yAxis] = convertPos(_x, _y);
    const piece = component.createObject(board, {
      name: Lua.evaluate(`(function()
        local Ch = require "packages.chess-games.nchess"
        return Ch:getPieceById(${id}).name
      end)()`),
      pieceId: id,
      xPos: _x,
      yPos: _y,
      x: xAxis,
      y: yAxis,
      origX: xAxis,
      origY: yAxis,
      z: 1,
    })
    piece.selectable = false;
    piece.goBackDuration = 200;
    piece.clicked.connect(selectPiece);
    pieces[id] = piece;

    piece.onStartDragPiece.connect(function(pieceId, xPos, yPos){
      clearAllHoverMark(true);
      let gridIdx = yPos * 8 + xPos;
      boardGridRepeater.itemAt(gridIdx).hover = true
      boardGridRepeater.itemAt(gridIdx).justShow = true
      const piece = pieces[pieceId]
      piece.selected = true
      selectPiece(piece)
    })
    piece.onEndDragPiece.connect(function(pieceId, xPos, yPos){
      let gridIdx = yPos * 8 + xPos;
      const piece = pieces[pieceId]
      if (piece.validMove) {
        clearAllHoverMark(true);
        let luaPosId = (yPos + 1) * 10 + (xPos + 1);
        if (Lua.evaluate("Self.role") === "black") {
          luaPosId = (8 - yPos) * 10 + (8 - xPos)
        }
        Lua.call("UpdateRequestUI", "NChess.PointItem", luaPosId, "click", {
          selected: true,
        } );
      } else {
        clearAllHoverMark();
        boardGridRepeater.itemAt(gridIdx).hover = true
      }
    }) 
    piece.onEnteredGrid.connect(function(pieceId, gridX, gridY){
      let gridIdx = gridY * 8 + gridX;
      clearAllHoverMark();
      boardGridRepeater.itemAt(gridIdx).hover = true
      const piece = pieces[pieceId]
      piece.allowedDrop = false
      if (gridPoints.itemAt(gridIdx).enabled) {
        piece.allowedDrop = true
      } else {
        piece.allowedDrop = false
      }
    })
    return piece
  }

  function clearAllHoverMark(cleanJustShow) {
    for (let id = 0; id < 64; id++) {
      boardGridRepeater.itemAt(id).hover = false
      if (cleanJustShow !== undefined) {
        boardGridRepeater.itemAt(id).justShow = false
      }
    }
  }

  function syncBoard(sender, data) {
    const component = Qt.createComponent("../../Components/Chess/NChess/Piece.qml");
    for (const id in pieces) {
      pieces[id].destroy();
      delete pieces[id];
    }
    pieces = {};

    for (let y = 0; y < 8; y++) {
      const xArr = data[y];
      for (let x = 0; x < 8; x++) {
        const id = data[y][x];

        if (id === 0) continue;
        initialPiece(id, x, y)
      }
    }
    const alphabetList = [
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'
    ];
    const color = Lua.evaluate("Self.role")
    for (let gid = 0; gid < 64; gid++) {
      const rect = boardGridRepeater.itemAt(gid);
      
      if (gid % 8 === 0) {
        if (color === "white") {
          rect.leftText.text = `${8 - Math.floor(gid / 8)}`
        } else {
          rect.leftText.text = `${Math.floor(gid / 8) + 1}`
        }
      }
      if (gid > 55) {
        if (color === "white") {
          rect.bottomText.text = alphabetList[gid - 56]
        } else {
          rect.bottomText.text = alphabetList[63 - gid]
        }
      }
    }
  }

  function playChess(sender, data) {
    roomScene.state = "active";
  }

  function deActivate() {
    for (const id in pieces) {
      pieces[id].selectable = false;
    }
    myPhoto.thinking = false;
    if (popupBox.item != null) {
      popupBox.item.close();
    }
    clearAllHoverMark(true)

    Lua.call("FinishRequestUI");
  }

  function doGoBack(piece, noAnim) {
    piece.selected = false;
    if (noAnim === undefined) {
      piece.goBack(true);
    } else {
      piece.goBack(false);
    }
  }

  function removePiece(pieceId) {
    const piece = pieces[pieceId]
    piece.origOpacity = 0;
    piece.origX = -62;
    piece.origY = -62;
    piece.destroyOnStop();
    doGoBack(piece, true);
  }

  function movePieceOut(sender, data) {
    const [ pieceId, fromX, fromY ] = data
    removePiece(pieceId)
  }

  function movePieceTo(sender, data) {
    const [ pieceId, fromX, fromY, x, y, noAnim ] = data;
    const piece = pieces[pieceId];
    const [xAxis, yAxis] = convertPos(x - 1, y - 1);
    for (const id in pieces) {
      if (id === pieceId) continue;
      const p = pieces[id];
      if (p.xPos === x - 1 && p.yPos === y - 1) {
        removePiece(id)
      }
    }

    piece.xPos = x - 1;
    piece.yPos = y - 1;
    piece.origX = xAxis;
    piece.origY = yAxis;
    if (noAnim === undefined) {
      doGoBack(piece);
    } else {
      doGoBack(piece, true);
    }
  }

  function addPieceTo(sender, data) {
    const [ pieceId, x, y ] = data;
    const piece = pieces[pieceId];
    piece.origOpacity = 1;
    movePieceTo(sender, [ pieceId, -1, -1, x, y, true ])
  }

  function preparePiece(sender, data) {
    const component = Qt.createComponent("../../Components/Chess/NChess/Piece.qml");
    const [ pid, pname ] = data
    initialPiece(pid, -1, -1)
  }

  function askForPromotion(sender, data) {
    roomScene.popupBox.sourceComponent = Qt.createComponent("../../Components/Chess/NChess/PromotionBox.qml");
    const pieceColor = data[0];
    const box = roomScene.popupBox.item;
    box.pieceColor = pieceColor;
    box.accepted.connect(() => {
      ClientInstance.replyToServer("", box.result);
    })
    roomScene.state = "active";
  }

  function moveFocus(sender, data) {
    const focuses = data[0];
    const command = data[1];
    const timeout = data[2] ?? (Config.roomTimeout * 1000);

    myPhoto.thinking = false;
    opponentPhoto.thinking = false;

    const photo = getPhoto(focuses[0]);
    photo.duration = Math.floor(timeout / 1000);
    photo.thinking = true;
  }

  function propertyUpdate(sender, data) {
    const uid = data[0];
    const property_name = data[1];
    const value = data[2];

    if (property_name !== "role") return;
    const photo = getPhoto(uid);
    photo.role = value === "white" ? '<font color="white"><b>白方</b></font>' : "<b>黑方</b>"
  }

  function updataLastMove(sender, data) {

    for (let id = 0; id < 64; id++) {
      boardGridRepeater.itemAt(id).lastMove = false;
    }

    const [role, fromX, fromY, x, y] = data;
    let gridFromIdx = (fromY - 1) * 8 + (fromX - 1);
    let gridIdx = (y - 1) * 8 + (x - 1);
    if (role === "black") {
      gridFromIdx = 63 - gridFromIdx;
      gridIdx = 63 - gridIdx;
    }
    boardGridRepeater.itemAt(gridFromIdx).lastMove = true;
    boardGridRepeater.itemAt(gridIdx).lastMove = true;
  }

  function netStateChanged(sender, data) {
    const id = data[0];
    let state = data[1];

    const photo = getPhoto(id);
    const t = {
      "online": "在线",
      "offline": "离线",
      "run": "逃跑",
    };
    photo.netState = t[state];
  }

  function doPlaySound(sender, data) {
    Backend.playSound(`./packages/chess-games/audio/${data}`);
  }

  function updatePENCode(sender, data) {
    buttonArea.penButton.penCode = data
  }

  function resetToInit() {
    App.quitPage();
    Lua.call("ResetClientLua");

    Mediator.notify(this, Command.BackToRoom);
  }

  function gameOver(sender, data) {
    if (data === "white") {
      winnerText.text = "白方胜利"
    } else if (data === "black") {
      winnerText.text = "黑方胜利"
    } else if (data === "white+s") {
      setSurrender("black")
      winnerText.text = "白方胜利"
    } else if (data === "black+s") {
      setSurrender("white")
      winnerText.text = "黑方胜利"
    } else {
      winnerText.text = "平局"
    }
    Backend.playSound(`./packages/chess-games/audio/over`)
    gameOverRect.visible = true;
  }

  function setSurrender(role) { //这个是反着的
    if (myPhoto.role === role) {
      opponentPhoto.surrendered = true
    } else {
      myPhoto.surrendered = true
    }
  }

  function updateRoundCount(sender, data) {
    roomScene.roundCount = data
  }

  function askToArmistice(sender, data) {
    roomScene.popupBox.sourceComponent = Qt.createComponent("../../Components/Chess/NChess/AskToArmisticeBox.qml");
    const box = roomScene.popupBox.item;
    box.accepted.connect(() => {
      ClientInstance.replyToServer("", box.result);
    })
    roomScene.state = "active";
  }

  Component.onCompleted: {
    addCallback("NChess.SyncBoard", syncBoard);
    addCallback("NChess.PlayChess", playChess);
    addCallback("NChess.MovePieceTo", movePieceTo);
    addCallback("NChess.MovePieceOut", movePieceOut);
    addCallback("NChess.UpdateNewPiece", preparePiece);
    addCallback("NChess.AddPieceTo", addPieceTo);
    addCallback("NChess.AskForPromotion", askForPromotion);
    addCallback("NChess.PlaySound", doPlaySound);
    addCallback("NChess.UpdateLastMove", updataLastMove);
    addCallback("NChess.UpdatePEN", updatePENCode);
    addCallback("NChess.UpdateRoundCount", updateRoundCount);
    addCallback("NChess.AskToArmistice", askToArmistice);

    addCallback(Command.UpdateRequestUI, applyChange);
    addCallback(Command.MoveFocus, moveFocus);
    addCallback(Command.PropertyUpdate, propertyUpdate);
    addCallback(Command.NetStateChanged, netStateChanged);
    addCallback(Command.GameOver, gameOver);

    // 填写玩家信息，简单暴力的。。。
    const id1 = Lua.evaluate("ClientInstance.players[1].id");
    const id2 = Lua.evaluate("ClientInstance.players[2].id");
    for (const pid of [id1, id2]) {
      const item = pid === Self.id ? myPhoto : opponentPhoto;
      item.playerid = pid;
      item.screenName = Lua.evaluate(`ClientInstance:getPlayerById(${pid}).player:getScreenName()`);
      item.avatar = Lua.evaluate(`ClientInstance:getPlayerById(${pid}).player:getAvatar()`);
    }
  }
}
